package com.beiing.tianshuai.tianshuai.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.NewDiscoveryPublishContentListAdapter;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.CodeBean;
import com.beiing.tianshuai.tianshuai.entity.PublishContentInfo;
import com.beiing.tianshuai.tianshuai.entity.UploadImgBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.freshnews.DiscoveryPreviewActivity;
import com.beiing.tianshuai.tianshuai.huodong.HuoDongPublishActivity;
import com.beiing.tianshuai.tianshuai.itemtouch.DefaultItemTouchHelper;
import com.beiing.tianshuai.tianshuai.itemtouch.DefaultItemTouchHelperCallback;
import com.beiing.tianshuai.tianshuai.presenter.DiscoveryPublishPresenter;
import com.beiing.tianshuai.tianshuai.util.ImgUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.view.DiscoveryPublishViewImpl;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.GlideImageLoader;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;
import com.yalantis.ucrop.UCrop;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileBatchCallback;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;

public class NewDiscoveryPublishActivity extends BaseActivity implements DiscoveryPublishViewImpl {

    /**
     * 返回按钮
     */
    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarBack;

    /**
     * 返回按钮
     */
    @BindView(R.id.publish_reminder)
    LinearLayout mReminder;

    /**
     * 页面标题
     */
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTitle;

    /**
     * 下一步
     */
    @BindView(R.id.toolbar_btn_publish)
    TextView mToolbarNext;

    /**
     * 添加图片
     */
    @BindView(R.id.btn_add_img)
    TextView mAddImg;

    /**
     * 添加文字
     */
    @BindView(R.id.btn_add_txt)
    TextView mAddTxt;

    /**
     * 添加视频
     */
    @BindView(R.id.btn_add_video)
    TextView mAddVideo;

    /**
     * 添加转载说明
     */
    @BindView(R.id.add_reprint_link)
    TextView mAddReprintLink;

    /**
     * 预览
     */
    @BindView(R.id.btn_preview)
    TextView mPreview;

    /**
     * 内容列表
     */
    @BindView(R.id.rv_content_list)
    RecyclerView mContentListView;

    /**
     * 标题
     */
    @BindView(R.id.et_title)
    EditText mContentTitle;

    public static final int REQUEST_CODE_ADD_TXT = 0;                   // 添加文字跳转界面请求码
    public static final int RESULT_CODE_WITHOUT_TXT = 1;                // 不带内容返回列表页
    public static final int RESULT_CODE_WITH_TXT = 2;                   // 带内容返回列表页
    public static final int PERMISSIONS_REQUEST_READ_CONTACTS = 3;      // 图片选择
    public static final int RESULT_CODE_INSERT_LINK = 4;                // 插入视频链接结果码
    public static final int REQUEST_CODE_ADD_VIDEO = 5;                 // 插入视频链接请求码
    public static final int REQUEST_CODE_ADD_REPRINT = 6;               // 插入转载链接请求码
    public static final int REQUEST_CODE_EDIT_TXT = 7;                  // 修改文字内容请求码

    public static final String TAG = "NewDiscoveryPublish";
    public static NewDiscoveryPublishActivity newDiscoveryPublishActivity;

    /**
     * 上下文关系
     */
    private Context mContext;

    /**
     * RecyclerView适配器
     */
    private NewDiscoveryPublishContentListAdapter mAdapter;

    /**
     * presenter
     */
    private DiscoveryPublishPresenter mPresenter = new DiscoveryPublishPresenter(this);

    /**
     * 所剪裁图片的位置
     */
    private int mCropPosition;

    /**
     * 是否为预览操作
     */
    private boolean isPreview;

    /**
     * 编辑页面类型
     * 0 = 活动发布
     * 1 = 新鲜事发布
     */
    private int mType;

    /**
     * RecyclerView Item的触摸事件监听
     */
    private DefaultItemTouchHelperCallback.OnItemTouchCallbackListener mOnItemTouchCallbackListener = new DefaultItemTouchHelperCallback.OnItemTouchCallbackListener() {
        @Override
        public void onSwiped(int adapterPosition) {
            if (mAdapter != null) {
                mAdapter.removeData(adapterPosition);
            }
        }

        @Override
        public boolean onMove(int srcPosition, int targetPosition) {
            if (mAdapter != null) {
                // 更新UI中item的位置
                mAdapter.swapMoved(srcPosition, targetPosition);
            }
            return false;
        }
    };

    public static void star(Context context, int type) {
        Intent intent = new Intent(context, NewDiscoveryPublishActivity.class);
        intent.putExtra("type", type);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_new_discovery_publish;
    }

    @Override
    protected void init() {
        mType = getIntent().getIntExtra("type", 0);
        mContext = this;
        initToolbar();
        initRecyclerView();
        initListener();
    }

    /**
     * 初始化Toolbar
     */
    private void initToolbar() {
        mToolbarBack.setVisibility(View.VISIBLE);
        mToolbarNext.setVisibility(View.VISIBLE);
        switch (mType) {
            case 0:
                mToolbarNext.setText("下一步");
                mToolbarTitle.setText("发布活动");
                mPreview.setVisibility(View.GONE);
                break;
            case 1:
                mToolbarNext.setText("发布");
                mToolbarTitle.setText("发布新鲜事");
                mPreview.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * 初始化列表及适配器
     */
    private void initRecyclerView() {
        mContentListView.setItemAnimator(new DefaultItemAnimator());
        mContentListView.setNestedScrollingEnabled(true);

        // 设置布局管理器
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mContentListView.setLayoutManager(manager);

        // 创建并设置适配器
        mAdapter = new NewDiscoveryPublishContentListAdapter(mContext);
        mContentListView.setHasFixedSize(true);
        mContentListView.setAdapter(mAdapter);

        // 设置ItemTouchListener
        DefaultItemTouchHelper defaultItemTouchHelper = new DefaultItemTouchHelper(mOnItemTouchCallbackListener);
        defaultItemTouchHelper.attachToRecyclerView(mContentListView);
        defaultItemTouchHelper.setDragEnable(true);
        defaultItemTouchHelper.setSwipeEnable(false);
    }

    /**
     * 初始化监听事件
     */
    private void initListener() {
        // 返回
        mToolbarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 添加文字
        mAddTxt.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                Intent intent = new Intent(mContext, PublishEditTextActivity.class);
                startActivityForResult(intent, REQUEST_CODE_ADD_TXT);
            }
        });

        // 修改文字
        mAdapter.setOnTxtClickListener(new NewDiscoveryPublishContentListAdapter.OnTxtClickListener() {
            @Override
            public void onEditTextListener(PublishContentInfo bean, int position) {
                Intent intent = new Intent(mContext, PublishEditTextActivity.class);
                intent.putExtra("isEdit", true);
                intent.putExtra("position", position);
                intent.putExtra("content", bean.getContent());
                startActivityForResult(intent, REQUEST_CODE_EDIT_TXT);
            }
        });

        // 添加图片
        mAddImg.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                List<PublishContentInfo> contentInfos = mAdapter.getList();
                int imgCount = 0;
                for (PublishContentInfo contentInfo : contentInfos) {
                    if (contentInfo.getType() == AppConstant.ITEM_TYPE_IMG) {
                        imgCount ++;
                        if (imgCount == 30) {
                            showShortText("最多只能添加30张图片噢~");
                            return;
                        }
                    }
                }
                checkSelfPermission();
            }
        });

        // 图片点击监听事件
        mAdapter.setOnImageViewClickListener(new NewDiscoveryPublishContentListAdapter.OnImageViewClickListener() {
            @Override
            public void onImageViewClick(View view, PublishContentInfo bean, int position) {
                view.setVisibility(view.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
            }

            @Override
            public void onDelClick(int position) {
                mAdapter.removeData(position);
            }

            @Override
            public void onReplaceClick(final View view, final PublishContentInfo bean, final int position) {
                List<String> path = new ArrayList<>();
                IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
                    @Override
                    public void onStart() {
                        LogUtils.i("----------------- 选图开始 -----------------", TAG);
                    }

                    @Override
                    public void onSuccess(List<String> photoList) {
                        for (String image : photoList) {
                            File file = new File(image);
                            if (file.length() >= 1024 * 1024 * 6) {
                                showShortText("仅支持上传6M以下的图片噢~");
                                break;
                            }
                            bean.setType(AppConstant.ITEM_TYPE_IMG);
                            bean.setContent("<img " +
                                    "src=\"" + image + "\"  alt=\"img\" />");
                            bean.setSrc(image);
                            view.setVisibility(view.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
                            mAdapter.updateData(bean, position);
                        }
                    }

                    @Override
                    public void onCancel() {
                        LogUtils.i("用户已取消", TAG);
                    }

                    @Override
                    public void onFinish() {
                        LogUtils.i("----------------- 选图结束 -----------------", TAG);
                    }

                    @Override
                    public void onError() {
                        LogUtils.e("----------------- 选图异常 -----------------", TAG);
                    }
                };
                galleryPicker(path, iHandlerCallBack);
            }

            @Override
            public void onImgPreview(View view, PublishContentInfo contentInfo) {
                view.setVisibility(view.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
                Intent intent = new Intent(mContext, SinglePicPreviewActivity.class);
                intent.putExtra("avatarUrl", contentInfo.getSrc());
                startActivity(intent);
            }

            @Override
            public void onImgCrop(View view, PublishContentInfo contentInfo, int adapterPosition) {
                Uri sourceUri = Uri.fromFile(new File(contentInfo.getSrc()));
                Uri destinationUri = Uri.fromFile(new File(getCacheDir(), "SimpleCropImage.jpg"));
                UCrop.of(sourceUri, destinationUri)
                        .withMaxResultSize(500, 500)
                        .start(NewDiscoveryPublishActivity.this);
                mCropPosition = adapterPosition;
            }
        });

        // 视频
        mAddVideo.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                int videoCount = 0;
                List<PublishContentInfo> contentInfos = mAdapter.getList();
                for (PublishContentInfo contentInfo : contentInfos) {
                    if (contentInfo.getType() == AppConstant.ITEM_TYPE_VIDEO) {
                        videoCount++;
                        if (videoCount == 3) {
                            showShortText("最多只能添加3个视频噢~");
                            return;
                        }
                    }
                }
                Intent intent = new Intent(mContext, PublishInsertUrlActivity.class);
                startActivityForResult(intent, REQUEST_CODE_ADD_VIDEO);
            }
        });

        // 插入转载链接
        mAddReprintLink.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                Intent intent = new Intent(mContext, PublishInsertReprintActivity.class);
                startActivityForResult(intent, REQUEST_CODE_ADD_REPRINT);
            }
        });

        // 预览
        mPreview.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                isPreview = true;
                String title = mContentTitle.getText().toString().trim();
                // 如果没有输入标题提示并返回
                if (TextUtils.isEmpty(title)) {
                    showShortText("请输入标题");
                    return;
                }
                List<PublishContentInfo> contentInfos = mAdapter.getList();
                // 如果没有输入内容提示并返回
                if (contentInfos.isEmpty()) {
                    showShortText("还没有输入内容噢~");
                    return;
                }
                List<File> images = new ArrayList<>();
                for (PublishContentInfo contentInfo : contentInfos) {
                    if (contentInfo.getType() == AppConstant.ITEM_TYPE_IMG) {
                        images.add(new File(contentInfo.getSrc()));
                    }
                }
                // 如果不存在图片则不执行上传图片的过程
                if (!images.isEmpty()) {
                    final File[] filesPath = images.toArray(new File[images.size()]);
                    // 压缩图片
                    Tiny.FileCompressOptions tinyOptions = new Tiny.BatchFileCompressOptions();
                    Tiny.getInstance().source(filesPath).batchAsFile().withOptions(tinyOptions).batchCompress(new FileBatchCallback() {
                        @Override
                        public void callback(boolean isSuccess, String[] outfile) {
                            List<String> outFiles = Arrays.asList(outfile);
                            List<File> finallyImages = new ArrayList<>();
                            for (int i = 0; i < outFiles.size(); i++) {
                                String s = outFiles.get(i);
                                finallyImages.add(new File(s));
                            }
                            for (int i = 0, filesPathLength = filesPath.length; i < filesPathLength; i++) {
                                File file = filesPath[i];
                                String fileType = ImgUtils.getFileType(file.getPath());
                                if ("gif".equals(fileType)) {
                                    finallyImages.set(i, file);
                                }
                            }
                            mPresenter.UploadImages(finallyImages);
                        }
                    });
                } else {
                    // 如果内容中不存在图片内容，那么直接拼接文字内容进行预览。
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0, contentInfosSize = contentInfos.size(); i < contentInfosSize; i++) {
                        PublishContentInfo contentInfo = contentInfos.get(i);
                        sb.append("<p>");
                        sb.append(contentInfo.getContent());
                        sb.append("</p>");
                    }
                    String content = sb.toString();
                    Intent intent = new Intent(mContext, DiscoveryPreviewActivity.class);
                    intent.putExtra("content", content);
                    intent.putExtra("title", title);
                    startActivity(intent);
                }
            }
        });

        // 列表点击事件
        mAdapter.setOnItemDeleteListener(new NewDiscoveryPublishContentListAdapter.OnItemDeleteListener() {
            @Override
            public void onDeleteListener(PublishContentInfo bean, final int position) {
                CustomDialog dialog = new CustomDialog(mContext, R.style.dialog, "确定要删除这条内容吗？", new CustomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm) {
                            dialog.dismiss();
                            mAdapter.removeData(position);
                        } else {
                            dialog.dismiss();
                        }
                    }
                }).setTitle("提示");
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
            }
        });

        // 发布
        mToolbarNext.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                CustomDialog dialog = new CustomDialog(mContext, R.style.dialog, "确认结束编辑并发布吗？", new CustomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm) {
                            dialog.dismiss();
                            publishDiscovery();
                        } else {
                            dialog.dismiss();
                        }
                    }
                }).setTitle("提示");
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
            }
        });
    }

    /**
     * 新鲜事编辑发布
     */
    private void publishDiscovery() {
        isPreview = false;
        String title = mContentTitle.getText().toString().trim();
        // 如果没有输入标题提示并返回
        if (TextUtils.isEmpty(title)) {
            showShortText("请输入标题");
            return;
        }
        List<PublishContentInfo> contentInfos = mAdapter.getList();
        // 如果没有输入内容提示并返回
        if (contentInfos.isEmpty()) {
            showShortText("还没有输入内容噢~");
            return;
        }
        List<File> images = new ArrayList<>();
        for (PublishContentInfo contentInfo : contentInfos) {
            if (contentInfo.getType() == AppConstant.ITEM_TYPE_IMG) {
                images.add(new File(contentInfo.getSrc()));
            }
        }
        // 如果不存在图片则不执行上传图片的过程
        if (!images.isEmpty()) {
            final File[] filesPath = images.toArray(new File[images.size()]);
            // 压缩图片
            Tiny.FileCompressOptions tinyOptions = new Tiny.BatchFileCompressOptions();
            Tiny.getInstance().source(filesPath).batchAsFile().withOptions(tinyOptions).batchCompress(new FileBatchCallback() {
                @Override
                public void callback(boolean isSuccess, String[] outfile) {
                    List<String> outFiles = Arrays.asList(outfile);
                    List<File> finallyImages = new ArrayList<>();
                    for (int i = 0; i < outFiles.size(); i++) {
                        String s = outFiles.get(i);
                        finallyImages.add(new File(s));
                    }
                    for (int i = 0, filesPathLength = filesPath.length; i < filesPathLength; i++) {
                        File file = filesPath[i];
                        String fileType = ImgUtils.getFileType(file.getPath());
                        if ("gif".equals(fileType)) {
                            finallyImages.set(i, file);
                        }
                    }
                    mPresenter.UploadImages(finallyImages);
                }
            });
        } else {
            // 如果内容中不存在图片内容，那么直接拼接文字内容进行预览。
            StringBuilder sb = new StringBuilder();
            for (int i = 0, contentInfosSize = contentInfos.size(); i < contentInfosSize; i++) {
                PublishContentInfo contentInfo = contentInfos.get(i);
                sb.append("<p>");
                sb.append(contentInfo.getContent());
                sb.append("</p>");
            }
            String content = getHtml(sb.toString());
            switch (mType) {
                case 0:
                    Intent intent = new Intent(mContext, HuoDongPublishActivity.class);
                    intent.putExtra("content", content);
                    intent.putExtra("title", title + "");
                    startActivity(intent);
                    break;
                case 1:
                    mPresenter.getPublishResult(content, UserInfoBean.getUid(mContext), title, "");
                    break;
            }
        }
    }

    // 动态权限申请
    private void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            LogUtils.i("需要授权", TAG);
            if (ActivityCompat.shouldShowRequestPermissionRationale(NewDiscoveryPublishActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                LogUtils.i("拒绝过了", TAG);
                // 提示用户如果想要正常使用，要手动去设置中授权。
                showShortText("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
                LogUtils.i("进行授权", TAG);
                ActivityCompat.requestPermissions(
                        NewDiscoveryPublishActivity.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        PERMISSIONS_REQUEST_READ_CONTACTS
                );
            }
        } else {
            LogUtils.i("不需要授权", TAG);
            // 进行正常操作
            selectImage();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                LogUtils.i("同意授权", TAG);
                // 进行正常操作。
                selectImage();
            } else {
                LogUtils.i("拒绝授权", TAG);
            }
        }
    }

    private void selectImage() {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                List<PublishContentInfo> contentInfos = mAdapter.getList();
                int imgCount = 0;
                for (PublishContentInfo contentInfo : contentInfos) {
                    if (contentInfo.getType() == AppConstant.ITEM_TYPE_IMG) {
                        imgCount ++;
                    }
                }
                for (String image : photoList) {
                    File file = new File(image);
                    if (file.length() >= 1024 * 1024 * 6) {
                        showShortText("无法上传大于6M的图片噢");
                        continue;
                    }
                    if ((imgCount++ >= 30)) {
                        showShortText("最对可上传30张图片");
                        break;
                    }
                    PublishContentInfo contentInfo = new PublishContentInfo(AppConstant.ITEM_TYPE_IMG, "<img " +
                            "src=\"" + image + "\"  alt=\"img\" />");
                    contentInfo.setSrc(image);
                    mReminder.setVisibility(View.GONE);
                    mAdapter.appendData(contentInfo, mAdapter.getItemCount());
                    mContentListView.smoothScrollToPosition(mAdapter.getItemCount() - 1);
                }
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        galleryPicker(path, iHandlerCallBack);
    }

    private void galleryPicker(List<String> path, IHandlerCallBack iHandlerCallBack) {
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(true, 9)           // 是否多选   默认：false
                .crop(false)                                        // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(NewDiscoveryPublishActivity.this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String content;
        switch (requestCode) {
            case REQUEST_CODE_ADD_TXT:
                if (data != null) {
                    content = data.getStringExtra("content");
                    if (!TextUtils.isEmpty(content)) {
                        mReminder.setVisibility(View.GONE);
                        PublishContentInfo contentInfo = new PublishContentInfo(AppConstant.ITEM_TYPE_TEXT, content);
                        mAdapter.appendData(contentInfo, mAdapter.getItemCount());
                        mContentListView.smoothScrollToPosition(mAdapter.getItemCount() - 1);
                    }
                }
                break;
            case REQUEST_CODE_EDIT_TXT:
                if (data != null) {
                    content = data.getStringExtra("content");
                    int position = data.getIntExtra("position", 0);
                    if (!TextUtils.isEmpty(content)) {
                        mAdapter.updateData(new PublishContentInfo(AppConstant.ITEM_TYPE_TEXT, content), position);
                    } else {
                        mAdapter.removeData(position);
                    }
                }
                break;
            case REQUEST_CODE_ADD_VIDEO:
                if (data != null) {
                    content = data.getStringExtra("link");
                    if (!TextUtils.isEmpty(content)) {
                        mReminder.setVisibility(View.GONE);
                        PublishContentInfo video = new PublishContentInfo(
                                AppConstant.ITEM_TYPE_VIDEO,
                                "<p><iframe " +
                                        "style=\"background-color:#EFEFEF\" " +
                                        "width=\"100%\" height=\"auto\" " +
                                        "frameborder=\"0\" src=\"" + content + "\" " +
                                        "allowfullscreen></iframe><p>"
                        );
                        mAdapter.appendData(video, mAdapter.getItemCount());
                        mContentListView.smoothScrollToPosition(mAdapter.getItemCount() - 1);
                    }
                }
                break;
            case REQUEST_CODE_ADD_REPRINT:
                if (data != null) {
                    String link = data.getStringExtra("link");
                    if (!TextUtils.isEmpty(link)) {
                        mReminder.setVisibility(View.GONE);
                        PublishContentInfo contentInfo = new PublishContentInfo(
                                AppConstant.ITEM_TYPE_REPRINT,
                                "<span style='color:#72888c; font-size:13px; float:right'>" +
                                        link + "</span>"
                        );
                        mAdapter.appendData(contentInfo, mAdapter.getItemCount());
                        mContentListView.smoothScrollToPosition(mAdapter.getItemCount() - 1);
                    }
                }
                break;
            case UCrop.REQUEST_CROP:
                if (resultCode == RESULT_OK) {
                    Uri croppedFileUri = UCrop.getOutput(data);
                    //获取默认的下载目录
                    String downloadsDirectoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
                    String filename = "UCrop_" + Calendar.getInstance().getTimeInMillis();
                    File saveFile = new File(downloadsDirectoryPath, filename);
                    //保存下载的图片
                    FileInputStream inStream = null;
                    FileOutputStream outStream = null;
                    FileChannel inChannel = null;
                    FileChannel outChannel = null;
                    try {
                        if (croppedFileUri != null) {
                            inStream = new FileInputStream(new File(croppedFileUri.getPath()));
                        }
                        outStream = new FileOutputStream(saveFile);
                        if (inStream != null) {
                            inChannel = inStream.getChannel();
                        }
                        outChannel = outStream.getChannel();
                        if (inChannel != null) {
                            inChannel.transferTo(0, inChannel.size(), outChannel);
                        }
                        String absolutePath = saveFile.getAbsolutePath();
                        File file = new File(absolutePath);
                        if (file.length() >= 1024 * 1024 * 6) {
                            showShortText("仅支持上传6M以下的图片噢~");
                            break;
                        }
                        PublishContentInfo contentInfo = new PublishContentInfo(AppConstant.ITEM_TYPE_IMG, "<img " +
                                "src=\"" + absolutePath + "\"  alt=\"img\" />");
                        contentInfo.setSrc(absolutePath);
                        mAdapter.updateData(contentInfo, mCropPosition);
                        showShortText("裁切后的图片保存在：" + absolutePath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (outChannel != null) {
                                outChannel.close();
                            }
                            if (outStream != null) {
                                outStream.close();
                            }
                            if (inChannel != null) {
                                inChannel.close();
                            }
                            if (inStream != null) {
                                inStream.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                }
        }
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "", false);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(UploadImgBean bean) {
        String freshCover = bean.getData().getFreshcover();
        String[] images;
        String[] freshCovers = freshCover.split(",");
        if (freshCover.contains(",")) {
            images = freshCovers;
        } else {
            images = new String[]{freshCover};
        }
        StringBuilder sb = new StringBuilder();
        int index = 0;
        List<PublishContentInfo> contentInfos = mAdapter.getList();
        for (int i = 0, contentInfosSize = contentInfos.size(); i < contentInfosSize; i++) {
            PublishContentInfo contentInfo = contentInfos.get(i);
            int type = contentInfo.getType();
            if (type == AppConstant.ITEM_TYPE_IMG) {
                contentInfo.setContent("<img " +
                        "src=\"http://www.tianshuai.com.cn/Public/Home/Uploads/freshcover/" +
                        images[index] + "\" alt=\"img\" />");
                index++;
            }
            sb.append("<p>");
            sb.append(contentInfo.getContent());
            sb.append("</p>");
        }
        String content = sb.toString();
        Intent intent;
        switch (mType) {
            case 0:
                intent = new Intent(mContext, HuoDongPublishActivity.class);
                intent.putExtra("content", content);
                intent.putExtra("title", mContentTitle.getText().toString().trim());
                startActivity(intent);
                break;
            case 1:
                if (isPreview) {
                    intent = new Intent(mContext, DiscoveryPreviewActivity.class);
                    intent.putExtra("content", content);
                    intent.putExtra("title", mContentTitle.getText().toString().trim());
                    startActivity(intent);
                } else {
                    String title = mContentTitle.getText().toString().trim();
                    String cover;
                    if (freshCover.contains(",")) {
                        StringBuilder coverSb = new StringBuilder();
                        for (int i = 0; i < freshCovers.length && i < 3; i++) {
                            String s = freshCovers[i];
                            if (i == 0) {
                                coverSb.append(s);
                            } else {
                                coverSb.append(",").append(s);
                            }
                        }
                        cover = coverSb.toString();
                    } else {
                        cover = freshCover;
                    }
                    mPresenter.getPublishResult(getHtml(content), UserInfoBean.getUid(mContext), title, cover);
                }
                break;
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        LogUtils.e(throwable.getMessage(), TAG);
        showShortText("操作失败");
    }

    @Override
    protected void onPause() {
        super.onPause();
        List<PublishContentInfo> contentInfos = mAdapter.getList();
        for (int i = 0, contentInfosSize = contentInfos.size(); i < contentInfosSize; i++) {
            PublishContentInfo contentInfo = contentInfos.get(i);
            if (contentInfo.getType() == AppConstant.ITEM_TYPE_VIDEO) {
                contentInfo.setOnPause(true);
                mAdapter.notifyItemChanged(i, contentInfo);
            }
        }
    }

    @Override
    public void publishSuccess(CodeBean bean) {
        if (bean.getCode() == 200) {
            showShortText("发布成功");
            finish();
        } else {
            showShortText("发布失败");
        }
    }

    private String getHtml(String html) {
        html = "<html> \n" +
                "<head> \n" +
                "<style type=\\\"text/css\\\"> \n" +
                "body {font-size:15px;}\n" +
                "</style> \n" +
                "</head> \n" +
                "<style type=\"text/css\">" +
                ".main_content{" +
                "width: 100%;" +
                "}" +
                ".main_content img{" +
                "width: 100%;" +
                "height: auto;" +
                "}" +
                "</style>" +
                "<body>\n" +
                "<div class='main_content'>" +
                html + "\n" +
                "</div>" +
                "</body>\n" +
                "</html>";
        LogUtils.i(html, "HTML");
        return html;
    }


    /**
     * 点击editText外部时隐藏软键盘
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                if (v != null) {
                    v.clearFocus();
                }
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v != null ? v.getWindowToken() : null, 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }
}
